# frozen_string_literal: true

class RuleEntity
  class GeneralRule
    class Condition < RuleEntity::GeneralRule
      # self.abstract_class = true

      has_many :rule_conditions, foreign_key: :general_rule_id, dependent: :destroy

      def deep_clone_to_draft
        entity = super

        entity.rule_conditions = rule_conditions.map(&:deep_clone_to_draft)
        entity
      end

      def update_draft(params)
        super
        update_conditions(params[:rule_conditions]) if params[:rule_conditions].present?
      end

      def force_validate
        super

        validate_conditions
      end

      def only_fire?(params)
        super
      end

      private

      def update_conditions(conditions_params)
        ordinal = 0
        rule_conditions.zip(conditions_params) do |output, params|
          if params.present?
            output.update! build_update_condition_params(ordinal, params)
          else
            output.destroy!
          end
          ordinal += 1
        end

        conditions_params[ordinal..]&.each_with_index do |params, index|
          rule_conditions.create! build_update_condition_params(ordinal + index, params)
        end
      end

      def build_update_condition_params(ordinal, params)
        { ordinal: ordinal, lvalue: params[:lvalue], operator: params[:operator], rvalue: params[:rvalue] }
      end

      def validate_conditions
        variable_names = schema.input_variables.map(&:name)

        rule_conditions.each { |condition| condition.validate(variable_names) }
      end
    end
  end
end
